package com.yuncheng.spcyApi.scheduleJob;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.entity.SpcyScheduleSetting;
import com.yuncheng.spcyApi.service.ISpcyScheduleSettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysJobRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Resource
    private ISpcyScheduleSettingService spcyScheduleSettingService;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为正常的定时任务
        List<SpcyScheduleSetting> jobList = spcyScheduleSettingService.list(new LambdaQueryWrapper<SpcyScheduleSetting>()
                .eq(SpcyScheduleSetting::getJobStatus, 1));
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SpcyScheduleSetting job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }
            logger.info("定时任务已加载完毕...");
        }
    }
}
